<?php

namespace app\admin\model;

use app\common\library\Auth;
use app\common\model\BaseModel;
use brand\tools\Random;

class Admin extends BaseModel
{

    public static function onBeforeInsert($admin)
    {
        unset($admin->group);
        $admin->salt = Random::alnum();
        $admin->password = (new Auth()) ->getEncryptPassword($admin->password, $admin->salt);
        if (!$admin->avatar){
            $admin->avatar = '/static/backend/avatar.png';
        }
    }

    public static function onAfterInsert($admin)
    {
        $group = request()->param('group');
        ( new AuthGroupAccess() )->setAccess($admin->id,$group);

    }

    public static function onBeforeUpdate($admin)
    {

        $changed = $admin->getChangedData();

        //如果有修改密码
        if (isset($changed['password'])) {
            if ($changed['password']) {
                $salt = Random::alnum();
                $admin->password = md5(md5($changed['password']).$salt);
                $admin->salt = $salt;
            } else {
                unset($admin->password);
            }
        }
        //所属组
        ( new AuthGroupAccess() )->setAccess($admin->id,$admin->group);


    }
}